package com.gt.quality.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gt.quality.config.SpringBeanUtil;
import com.gt.quality.system.entity.SysRole;
import com.gt.quality.system.entity.SysUserRole;
import com.gt.quality.system.entity.dto.SysUserDTO;
import com.gt.quality.system.entity.vo.UserBindRole;
import com.gt.quality.system.mapper.SysUserRoleMapper;
import com.gt.quality.base.pojo.BaseLimitRequest;
import com.gt.quality.base.pojo.LayerListViewObject;
import com.gt.quality.base.pojo.Resp;
import com.gt.quality.system.service.SysRoleService;
import com.gt.quality.system.service.SysUserRoleService;
import jakarta.annotation.Resource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;
import java.util.Optional;

/**
 * 用户和角色关联表(SysUserRole)表服务实现类
 *
 * @author makejava
 * @since 2026-11-25 16:30:08
 */
@Service("sysUserRoleService")
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private SysRoleService sysRoleService;


    /**
     * Description:  分页查询
     *
     * @param limitRequest 分页查询参数
     * @author: makeJava
     * @date: 2026-02-02 14:57:06
     * @return:com.baomidou.mybatisplus.core.metadata.IPage
     */
    @Override
    public IPage<SysUserRole> queryLimitPage(BaseLimitRequest<SysUserRole> limitRequest) {
        SysUserRole requestBody = limitRequest.getRequestBody();
        IPage<SysUserRole> page = getByPageParam(limitRequest);
        JSONObject thisObj = JSONObject.from(requestBody);
        QueryWrapper<SysUserRole> queryWrapper = queryWrapperBuilder(thisObj, limitRequest);
        return sysUserRoleMapper.selectPage(page, queryWrapper);
    }

    /**
     * Description:  批量新增优化版
     *
     * @param entityList entityList
     * @author: makeJava
     * @date: 2026-02-02 19:54:59
     */
    @Override
    public Integer saveBatchByEasyBaseMapper(List<SysUserRole> entityList) {

        return sysUserRoleMapper.insertBatchSomeColumn(entityList);
    }

    @Override
    public Resp<LayerListViewObject> queryForUserId(String userId) {
        List<SysRole> data = sysUserRoleMapper.queryForUserId(userId);
        List<SysRole> currentRoles = Optional.ofNullable(data).orElse(List.of());
        List<SysRole> allList = sysRoleService.list(new QueryWrapper<>());
        List<SysRole> noHaveRoles = allList.stream().filter(item -> !currentRoles.contains(item)).toList();
        LayerListViewObject layerListViewObject = new LayerListViewObject();
        layerListViewObject.setCurrentLayer(currentRoles);
        layerListViewObject.setNextLayer(noHaveRoles);
        return Resp.ok(layerListViewObject);
    }

    @Override
    public Resp<Object> queryForRoleId(String roleId) {
        List<SysUserDTO> data = sysUserRoleMapper.queryForRoleId(roleId);
        return Resp.ok(data);
    }

    @Override
    public Resp<Boolean> roleBindUser(UserBindRole userBindRole) {
        List<String> roleIds = userBindRole.getRoleIds();
        if (CollUtil.isNotEmpty(roleIds)) {
            List<SysUserRole> sysUserRoles = roleIds.stream().map(item -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(Long.valueOf(userBindRole.getUserId()));
                sysUserRole.setRoleId(Long.valueOf(item));
                return sysUserRole;
            }).toList();
            saveBatchByEasyBaseMapper(sysUserRoles);
        }
        return Resp.ok();
    }

    @Override
    public Resp<Boolean> roleRemoveUser(UserBindRole userBindRole) {
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userBindRole.getUserId());
        wrapper.in(SysUserRole::getRoleId, userBindRole.getRoleIds());
        sysUserRoleMapper.delete(wrapper);
        return Resp.ok();
    }

    /**
     * 往上传递 SqlSessionFactory
     *
     * @return SqlSessionFactory
     */
    @Override
    public SqlSessionFactory getSqlSessionFactory() {
        return super.getSqlSessionFactory();
    }

    /**
     * 往上传递 Mapper
     *
     * @return Mapper
     */
    @Override
    public Class<?> getThisMapperClass() {
        return SysUserRoleMapper.class;
    }

    /**
     * 往上传递 Transaction
     *
     * @return Transaction
     */
    @Override
    public TransactionTemplate getSpringTx() {
        return SpringBeanUtil.getBean(TransactionTemplate.class);
    }

}


